package com.niiwoo.civet.trade.service.local.refund;

import com.niiwoo.civet.account.dto.common.sendmessage.InvestReceiveDTO;
import com.niiwoo.civet.trade.constant.DatePatternConstant;
import com.niiwoo.civet.trade.dao.entity.InvestorReceiveRecord;
import com.niiwoo.civet.trade.dao.mapper.InvestorReceiveRecordMapperExt;
import com.niiwoo.civet.trade.dto.response.InvestorReceiveResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 回款-投资人短信通知
 *  
 * @author: kevin.jia
 * @version 1.0.0
 */
@Slf4j
@Service
public class InvestorReceiveNoticeService {
    @Autowired
    private InvestorReceiveRecordMapperExt investorReceiveRecordMapperExt;

    /**
     * 投资回款通知(通知+短信)
     * 查询昨日回款记录、次日7点后统计发送前一日投资回款通知
     * 
     * @return
     */
    public List<InvestReceiveDTO> selectYesterdayInvestorReceiveNotice() {
		DateTime createTime = new DateTime().minusDays(1);
		List<InvestorReceiveResponseDTO> receiveRecordList = investorReceiveRecordMapperExt.selectYesterdayInvestorReceiveNotice(createTime.toDate());
		List<InvestReceiveDTO> investReceiveDTOList = new ArrayList<>();
		receiveRecordList.forEach(record -> {
			InvestReceiveDTO receiveDTO = new InvestReceiveDTO();
			receiveDTO.setId(record.getId());
			receiveDTO.setUserId(record.getInvestorUserId());
			receiveDTO.setReceiveCorpus(record.getReceiveCorpus());
			receiveDTO.setReceiveInterest(record.getReceiveInterest());
			receiveDTO.setReceiveBidCount(record.getReceiveBidCount());
			receiveDTO.setReceiveOverdueFine(record.getReceiveOverdueFine());
			receiveDTO.setReceiveAmount(record.getReceiveCorpus().add(record.getReceiveInterest()).add(record.getReceiveOverdueFine()));
			receiveDTO.setReceiveDate(FastDateFormat.getInstance(DatePatternConstant.YYYY_MM_DD).format(record.getReceiveDate()));
			Integer overDebtCount = investorReceiveRecordMapperExt.selectOverDebtCountByInvestorUserId(record.getInvestorUserId(), createTime.toDate());
			receiveDTO.setOverDebtCount(overDebtCount);
			investReceiveDTOList.add(receiveDTO);
		});
		return investReceiveDTOList;
    }

    
	/**
	 * 更新投资人回款记录发送时间
	 * 
	 * @param receiveRecord
	 */
	public void updateInvestorReceiveRecord(InvestorReceiveRecord receiveRecord) {
		investorReceiveRecordMapperExt.updateByInvestorUserId(receiveRecord);
	}
    
    /**
     * 删除投资人回款记录
     * 
     * @param receivedDate
     */
	public void deleteByReceivedDate(Date receivedDate) {
		investorReceiveRecordMapperExt.deleteByReceivedDate(receivedDate);
	}
}